// pages/memberCard/memberCard.js
let ani1 = null
let ani2 = null
const api = require('../../utils/interface.js')
const qrcode = require('../../utils/qrCode.js')
const math = require('../../utils/math.js')
const webSocket = require("../../utils/websocket.js")
const wxcode = require('../../utils/wxCode.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    animation: null,
    state: 1,
    animation2: null,
    uuid: "",
    details: {},
    radio: false,
    cardId: "",
    distanceInfo: {
      lat: '',
      lot: ''
    },
    imagePath:"",
    productId:"",
    name:"",
    text:"",
    index:-1,
    timer:null
  },
  onLoad: function(options) {
    wx.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: "#ffffff"
    })
    let that = this
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        that.data.distanceInfo.lat = res.latitude
        that.data.distanceInfo.lot = res.longitude
      }
    })
    console.log(options)
    this.getMemberInfo()
    this.memberCardetails(options.cardId)
    this.data.cardId = options.cardId
    this.data.uuid = options.uuid
    ani1 = wx.createAnimation({
      duration: 500,
      delay: 100,
      timingFunction: 'ease',
    })
    ani2 = wx.createAnimation({
      duration: 500,
      delay: 100,
      timingFunction: 'ease',
    })
    
    if (options.type) {
      this.setData({
        state: 1
      })
      this.start()
    } else {
    }
    this.createCode()
    this.data.timer = setInterval(()=>{
      this.createCode()
    },60000)
    this.setData({
      productId: options.productId,
      name: options.name,
      index:options.index
    })
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2];
    prevPage.setData({
      isShow: false
    })
    this.repeatSocket()
    this.getText()
  },
  // 跳转到优惠券
  goGift(){
    wx.navigateTo({
      url: '/pages/couponcard/couponcard?membercardId=' + this.data.cardId
    })
  },
  getMemberInfo() {
    let user = wx.getStorageSync('userInfo')
    api.getMemberInfo({
      id: user.id
    }).then(res => {
      if (!res.data.result.phone && user.loginCount > 1) {
        wx.reLaunch({
          url: '/pages/login/login',
        })
      }
    })
  },
  createCode() {
    // setCodeExpirationTime
    console.log("UUID=", 'cyf_' + this.data.uuid)
    let that = this
    console.log(randomNum(1000,9999))
    let uuid = 'xcx_' + randomNum(1000, 9999) + this.data.uuid
    let imgpath = wxcode.createQrCodeImg(uuid)
    this.setCodeExpirationTime(uuid)
    this.setData({
      imagePath: imgpath
    })
    function randomNum(minNum, maxNum) {
      switch (arguments.length) {
        case 1:
          return parseInt(Math.random() * minNum + 1, 10);
          break;
        case 2:
          return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
          //或者 Math.floor(Math.random()*( maxNum - minNum + 1 ) + minNum );
          break;
        default:
          return 0;
          break;
      }
    } 
  },
  start() {
    if (this.data.state == 1) {
      ani1.top('568rpx').height('900rpx').step()
      ani2.opacity(1).step()
      this.setData({
        animation: ani1.export(),
        state: 2,
        
      }, function() {
        setTimeout(() => {
          this.setData({
            animation2: ani2.export(),    
          })
        }, 500)
      })
    } else {
      ani1.top('100vh').height('130rpx').step()
      ani2.opacity('0').step()
      this.setData({
        animation: ani1.export(),
        animation2: ani2.export(),
      }, function() {
        setTimeout(() => {
          this.setData({
            animation2: ani2.export(),
          }, function() {
            setTimeout(() => {
              this.setData({
                state: 1
              })
            }, 400)
          })
        }, 500)
      })
    }

  },
  // 定时刷新请求后台会员吗
  setCodeExpirationTime(uuid){
    api.setCodeExpirationTime({ uuid}).then(res=>{
      console.log(res.data.result,"xiusi")
    })
  },
  // 会员卡详情
  memberCardetails(id) {
    api.selectDetailsById({
      memberCardId: id
    }).then(res => {
      console.log(res.data.result,'我的卡详情')
      res.data.result.rechargeBalance_ = math.divide(res.data.result.rechargeBalance, 100)
      res.data.result.redGiftAmount_ = math.divide(res.data.result.redGiftAmount, 100)
      if (res.data.result.firstFlag == '1') {
        this.setData({
          radio: true
        })
      } else {
        if(this.data.index=='0'){
          this.setData({
            radio: true
          })
        }else{
          this.setData({
            radio: false
          })
        }
        
      }
      switch (res.data.result.productName){
        case '汽油':
          res.data.result.color ="#4A8BFC"
        break;
        case '柴油':
          res.data.result.color = "#F56C6C"
          break;
        case 'LNG':
          res.data.result.color = "#02B663"
          break;
      }
      this.setData({
        details: res.data.result
      })
    })
  },
  setfirstFlag(e) {
    if (this.data.radio) {
      return false
    }
    api.editMemberCardFirst({
      memberCardId: this.data.details.id
    }).then(res => {
      wx.showToast({
        title: res.data.message,
        icon: 'none',
        duration: 2000
      })
    })
    this.setData({
      radio: !this.data.radio
    })
  },
  go_racharge() {
    wx.navigateTo({
      url: '/pages/memberReacarge/memberRecharge?memberCardId=' + this.data.details.id + '&stationId=' + this.data.details.storeId + '&parductId=' + this.data.details.productId,
    })
  },
  lossCard() {
    let that = this
    wx.showModal({
      title: '确认解绑实体卡吗？', 
      content: '解绑实体卡后，实体卡片将不可使用',
      success(res) {
        if (res.confirm) {
          api.lossCard({
            cardId: that.data.cardId
          }).then(res => {
            console.log(res.data)
            if (res.data.status == 200) {
              wx.showModal({
                title: '提示',
                content: res.data.code,
                showCancel: false,
                success(res) {

                }
              })
            } else {
              wx.showModal({
                title: '提示',
                content: res.data.code,
                showCancel: false,

              })
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  reverStation() {
    let id = wx.getStorageSync('userInfo').id
    let cityId = wx.getStorageSync('cityId')
    wx.navigateTo({
      url: '/pages/webView/webview?url= ' + getApp().globalData.url + 'stationList&distanceInfo=' + JSON.stringify(this.data.distanceInfo) + '&memberId=' + id + '&cityId=' + cityId + '&memberCardId=' + this.data.cardId
    })
  },
  repeatSocket() {
    console.log(99)
    let timer = setTimeout(() => {
      let user = wx.getStorageSync("userInfo")
      if (user) {
        webSocket.connectSocket();
        webSocket.onSocketMessageCallback = getApp().onSocketMessageCallback;
        console.log(99)
        webSocket.sendSocketMessage({
          msg: String(user.id),
        })
        clearTimeout(timer)
      } else {
        this.repeatSocket()
      }
    }, 1000)
  },
  getText(){
    api.getTextAdvert({}).then(res=>{
      console.log(res.data.result,'okokok')
      this.setData({
        text:res.data.result[0].name
      })
    })
  },
  // 跳转会员卡
  setPass(){
    console.log(this.data.details)
    wx.navigateTo({
      url: '/pages/userset/setPass/setPass?cardId=' + this.data.details.id + '&paySwitch=' + this.data.details.paySwitch,
    })
  },
  onUnload(){
    console.log('socket关闭')
    webSocket.closeSocket()
    clearInterval(this.data.timer)
  }
})